import type { ProColumns } from '@ant-design/pro-components';
import { ModalForm, ProFormDatePicker, ProFormMoney, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import type { SaveProgrammeBookData } from '@fill/client';
import { queryClient, rspc } from '@fill/client';
import type { FormInstance } from 'antd';
import { Button, Card, Col, Form, Row, Space, Tabs, Typography, notification } from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';
import type { HANDLE_APPROVAL_TYPE, HANDLE_STATUS_TYPE } from '../../constants/default';
import { APPROVAL_REPORT_ENUM, APPROVAL_STATE, HANDLE_STATUS, NODE_TYPE, QUESTION_ENUM, STATUS_VALUE } from '../../constants/default';
import { BOOK_STATUS, BOOK_STATUS_ENUM, BOOK_STATUS_TEXT } from '../../constants/select';
import { checkStateUpdate } from '../../util/state';
import type { OpinionSchema } from '../opinion/interface';
import { OpinionBase, OpinionProgramme } from '../programme/Detail';
import { Records } from '../rectification/Records';
import { Complete } from './Complete';
import { Duty } from './Duty';

export const OpinionBook: React.FC<OpinionSchema> = (records) => {
  const [status, setStatus] = useState(records.programme_book?.rectification_status);

  useEffect(() => {
    setStatus(records.programme_book?.rectification_status);
  }, [records]);

  return (
    <Card title="整改报告">
      <Row>
        <Col span={12}>
          <ProFormSelect label="整改状态" name={['programme_book', 'rectification_status']} labelCol={{
            span: 6,
          }} rules={[
            {
              required: true,
              message: '请选择整改状态',
            },
          ]} options={BOOK_STATUS} fieldProps={{
            onChange: (value) => {
              console.log(records);
              setStatus(value);
            },
          }} />
        </Col>
        <Col span={12}>
          {
            String(status) === String(BOOK_STATUS_ENUM.PROCCESS) && (
              <ProFormDatePicker label="完成时限" name={['programme_book', 'book_completed_at']} width="md" labelCol={{
                span: 6,
              }} rules={[
                {
                  required: true,
                  message: '请选择完成时限',
                },
              ]} />
            )
          }
        </Col>
        <Col span={24}>
          <ProFormTextArea label="整改完成情况" name={['programme_book', 'completion_remark']} rules={[
            {
              required: true,
              message: '请输入整改完成情况',
            },
          ]} />
        </Col>
      </Row>
    </Card>
  );
};

interface IBookEffectProps {
  readonly: boolean
  form: FormInstance
}

export const BookEffect: React.FC<IBookEffectProps> = ({ readonly, form }) => {
  return (
    <Row>
      <Col span={12}>
        <ProFormMoney label="清缴资金情况" initialValue={0.00} locale="en-US"
          min={0}
          name={['programme_book', 'payment_found']} labelCol={{
            span: 6,
          }} addonAfter={<Typography.Text>万元</Typography.Text>}
          fieldProps={{ precision: 2 }}
          placeholder="请输入清缴资金"
        />
      </Col>
      <Col span={10}>
        <ProFormText label="其他" name={['programme_book', 'other']} />
      </Col>
      <Col span={24}>
        <ProFormSelect mode="tags" width="xl" placeholder={'请输入组织'} label="因巡察整改不力问责党组织" name={['programme_book', 'other_organization']} labelCol={{
          span: 3,
        }} />
      </Col>
      <Col span={24}>
        <Duty readonly={readonly} form={form} />
      </Col>
      <Col span={24}>
        <Complete readonly={readonly} form={form} />
      </Col>
    </Row>
  );
};

export const BookDetail = (records: OpinionSchema & { readonly: boolean; module: string }) => {
  const { readonly, ...record } = records;
  const [open, setOpen] = useState(false);
  const saveProgrammeBook = rspc.useMutation('opnions.save_programme_book');

  const [form] = Form.useForm<any>();

  useEffect(
    () => {
      form.setFieldsValue({
        ...record,
        programme_book: {
          ...record.programme_book,
          completion_remark: record.programme_book?.completion_remark?.replaceAll('<br />', '\n'),
          investigation: (!!record.programme_book?.investigation && JSON.parse(record.programme_book?.investigation)) || [],
          perfect: (!!record.programme_book?.perfect && JSON.parse(record.programme_book?.perfect)) || [],
          other_organization: (!!record.programme_book?.other_organization && record.programme_book?.other_organization.split(',')) || [],
        },
      });
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [record],
  );

  async function handleSubmit(tmp = false) {
    try {
      await form.validateFields();
    }
    catch (error) {
      notification.error({
        message: '校验失败',
      });
      return;
    }

    const { programme_book } = form.getFieldsValue();

    const _programme_book = {
      ...record.programme_book,
      ...programme_book,
    };

    console.log(form.getFieldsValue());

    const params: SaveProgrammeBookData = {
      uuid: record.uuid,
      department: _programme_book?.department || '',
      leader: _programme_book?.leader || '',
      user: _programme_book?.user || '',
      completed_at: (!!_programme_book?.completed_at && dayjs(_programme_book?.completed_at).format('YYYY-MM-DD HH:mm:ss')) || '',
      book_completed_at: (!!_programme_book?.book_completed_at && dayjs(_programme_book?.book_completed_at).format('YYYY-MM-DD HH:mm:ss')) || '',
      is_rectification: _programme_book?.is_rectification || '',
      proposal: _programme_book?.proposal || '',
      measures: _programme_book?.measures || '',
      rectification_status: _programme_book?.rectification_status || '',
      completion_remark: (_programme_book?.completion_remark && _programme_book?.completion_remark.replaceAll('\n', '<br />')) || '',
      payment_found: (_programme_book?.payment_found && String(_programme_book?.payment_found)) || '0',
      other: _programme_book?.other || '',
      other_organization: (!!_programme_book?.other_organization && (typeof (_programme_book?.other_organization) === 'string' ? _programme_book?.other_organization : (_programme_book?.other_organization as unknown as string[]).join())) || '',
      investigation: JSON.stringify(_programme_book.investigation ? _programme_book.investigation : []),
      perfect: JSON.stringify(_programme_book.perfect ? _programme_book.perfect : []),
      status: _programme_book?.status || '',
      book_status: tmp ? STATUS_VALUE.PENDING : STATUS_VALUE.PROCESSED,
    };

    console.log(params);

    await saveProgrammeBook.mutateAsync({
      arg: params,
    }, {
      async onSuccess() {
        await queryClient.refetchQueries({
          queryKey: ['opnions.get'],
        });
      },
    });

    setOpen(false);
  }

  // const tabsCollection = [
  //   {
  //     key: '1',
  //     label: '整改方案',
  //     children: <Space direction="vertical" style={{
  //       display: 'flex',
  //     }}>
  //       <OpinionBase readonly />
  //       <OpinionProgramme readonly />
  //       <OpinionBook {...records} />
  //     </Space>,
  //   },
  //   {
  //     key: '2',
  //     label: '整改成效',
  //     children: <BookEffect key="effect" {...records} />,
  //   },
  //   {
  //     key: '3',
  //     label: '提交审批记录',
  //     children: <OpinionRecords key="records" {...records} />,
  //   },
  // ];

  return (
    <>
      <a key="detail" onClick={() => setOpen(true)}>{readonly ? '查看' : '编辑'}</a>
      <ModalForm<OpinionSchema>
        width={1000}
        title="整改台账"
        // trigger={
        //   <a key="detail">{readonly ? '查看' : '编辑'}</a>
        // }
        layout="horizontal"
        labelCol={{
          span: 3,
        }}
        labelWrap={true}
        modalProps={{
          destroyOnClose: true,
        }}
        onOpenChange={(e) => {
          setOpen(e);
        }}
        form={form}
        readonly={readonly}
        open={open}
        submitter={{
          render() {
            return <div style={{
              display: 'flex',
              flex: 1,
              justifyContent: 'center',
            }}>
              {[
                !readonly && <Button type="primary" key="tmp" onClick={() => handleSubmit(true)}>暂存</Button>,
                !readonly && <Button type="primary" key="submit" onClick={() => handleSubmit()}>确定</Button>,
                <Button key="cancel" onClick={() => setOpen(false)}>取消</Button>,
              ]}
            </div>;
          },
        }}
        // initialValues={{
        //   ...record,
        //   programme_book: {
        //     ...record.programme_book,
        //     other_organization: (record.programme_book?.other_organization && record.programme_book?.other_organization.split(',')) || [],
        //   },
        // }}
        // onFinish={async ({ programme_book }) => {
        //   console.log({
        //     ...programme_book,
        //   });

        //   const _programme_book = {
        //     ...records.programme_book,
        //     ...programme_book,
        //   };

        //   try {
        //     const params: SaveProgrammeBookData = {
        //       uuid: record.uuid,
        //       department: _programme_book?.department || '',
        //       leader: _programme_book?.leader || '',
        //       user: _programme_book?.user || '',
        //       completed_at: (_programme_book?.completed_at && dayjs(_programme_book?.completed_at).format('YYYY-MM-DD HH:mm:ss')) || '',
        //       book_completed_at: (_programme_book?.completed_at && dayjs(_programme_book?.book_completed_at).format('YYYY-MM-DD HH:mm:ss')) || '',
        //       is_rectification: _programme_book?.is_rectification || '',
        //       proposal: _programme_book?.proposal || '',
        //       measures: _programme_book?.measures || '',
        //       rectification_status: _programme_book?.rectification_status || '',
        //       completion_remark: _programme_book?.completion_remark || '',
        //       payment_found: _programme_book?.payment_found || '',
        //       other: _programme_book?.other || '',
        //       other_organization: (_programme_book?.other_organization && (typeof (_programme_book?.other_organization) === 'string' ? _programme_book?.other_organization : (_programme_book?.other_organization as unknown as string[]).join())) || '',
        //       investigation: _programme_book?.investigation || '',
        //       perfect: _programme_book?.perfect || '',
        //       status: _programme_book?.status || '',
        //       book_status: '2',
        //     };

        //     console.log(params);

        //     await saveProgrammeBook.mutateAsync({
        //       arg: params,
        //     }, {
        //       onSuccess() {
        //         queryClient.refetchQueries({
        //           queryKey: ['opnions.get'],
        //         });
        //       },
        //     });

        //     return true;
        //   }
        //   catch (error) {
        //   }
        // }}
      >
        {
          readonly
            ? (
            <Tabs defaultActiveKey="1" items={[
              {
                key: '1',
                label: '整改方案',
                children: <Space direction="vertical" style={{
                  display: 'flex',
                }}>
                  <OpinionBase readonly />
                  <OpinionProgramme readonly />
                  <OpinionBook {...records} />
                </Space>,
              },
              {
                key: '2',
                label: '整改成效',
                children: <BookEffect key="effect" readonly={readonly} form={form} />,
              },
              {
                key: '3',
                label: '提交审批记录',
                children: <Records key="records" module={NODE_TYPE.BOOK} relation_uuid={records.uuid} />,
              },
            ]} />
              )
            : (
              <Tabs defaultActiveKey="1" items={[
                {
                  key: '1',
                  label: '整改方案',
                  children: <Space direction="vertical" style={{
                    display: 'flex',
                  }}>
                    <OpinionBase readonly />
                    <OpinionProgramme readonly required={false} />
                    <OpinionBook {...records} />
                  </Space>,
                },
                {
                  key: '2',
                  label: '整改成效',
                  children: <BookEffect key="effect" readonly={readonly} form={form} />,
                },

              ]} />
              )
        }
      </ModalForm>
    </>

  );
};

export const useBook = () => {
  const columns: ProColumns<any>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '问题分类',
      dataIndex: 'slug',
      valueEnum: QUESTION_ENUM,
      width: 300,
    },
    {
      title: '问题方面',
      dataIndex: 'description',
      width: 250,
    },
    {
      title: '具体问题',
      dataIndex: 'content',
      width: 410,
    },
    {
      title: '完成时限',
      width: 160,
      render(_, { programme_book }) {
        return (<div>{(!!programme_book?.book_completed_at && dayjs(programme_book?.book_completed_at).format('YYYY-MM-DD')) || '-'}</div>);
      },
    },
    {
      title: '整改状态',
      width: 100,
      render(_, { programme_book }) {
        return (<div>{(!!programme_book?.rectification_status && BOOK_STATUS_TEXT[+programme_book.rectification_status]) || '-'}</div>);
      },
    },
    {
      title: '责任人',
      width: 140,
      render(_, { programme_book }) {
        return (<div>{programme_book?.user || '-'}</div>);
      },
    },
    {
      title: '审批意见',
      width: 250,
      render(_, { programme_book }) {
        return APPROVAL_REPORT_ENUM[+programme_book?.book_note as keyof typeof APPROVAL_REPORT_ENUM] || '-';
      },
    },
    {
      title: '审批状态',
      dataIndex: 'state',
      width: 140,
      render(_, { programme_book }) {
        return (
          <div>{(programme_book?.state && APPROVAL_STATE[programme_book.state as HANDLE_APPROVAL_TYPE]) || '-'}</div>
        );
      },
    },
    {
      title: '处理状态',
      dataIndex: 'book_status',
      render(_, { programme_book }) {
        return (
          <div>{(programme_book?.book_status && HANDLE_STATUS[programme_book.book_status as HANDLE_STATUS_TYPE]) || '-'}</div>
        );
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 140,
      render: (_text, record, _, _action) => [
        <BookDetail key="detail" {...record} readonly />,
        checkStateUpdate(record?.programme_book?.book_state || '') && <BookDetail key="edit" {...record} readonly={false} />,
      ],
    },
  ];

  return {
    columns,
  };
};
